package com.lebang.medicalInquiry.model.chat;

import com.alibaba.fastjson.JSONObject;


import com.lebang.medicalInquiry.utils.TextUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;

import javax.annotation.Nullable;
import java.io.IOException;
import java.util.function.Consumer;

@Slf4j
public abstract class AbstractEventSourceListener extends EventSourceListener {

    public abstract void onMsg(String data);
    public abstract void onError(Throwable var1);

    protected Consumer<String> onComplate = (s) -> {
    };
    @Override
    public void onOpen(EventSource eventSource, Response response) {
        super.onOpen(eventSource, response);
    }

    // 当监听到服务器数据传回时  会触发
    @Override
    public void onEvent(EventSource eventSource, @Nullable String id, @Nullable String type, String data) {
        if(!"[DONE]".equals(data)){
            ChatRespone chatRespone = JSONObject.parseObject(data, ChatRespone.class);
            ChatRespone.Choices choices = chatRespone.getChoices().get(0);
            String finishReason = choices.getFinishReason();
            if(!TextUtil.isEmpty(finishReason)&&finishReason.contains("stop")){
                this.onComplate.accept("全部传完啦");
            }else{

                String content = choices.getDelta().getContent();
                if(!TextUtil.isEmpty(content)){
                    this.onMsg(content);
                }

            }
        }


    }

    @Override
    public void onClosed(EventSource eventSource) {
        super.onClosed(eventSource);
    }

    @Override
    public void onFailure(EventSource eventSource, @Nullable Throwable t, @Nullable Response response) {
        try {
            log.error("response info: {}",response.body().string());
            log.error("error info: {}",t.getMessage());
            log.error("error detail info: {}",t.getCause().getMessage());
            this.onError(t);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void setOnComplate(Consumer<String> onComplate) {
        this.onComplate = onComplate;
    }
}
